﻿using Common;
using Common.Enums;
using FreeSql.Context;
using FreeSql.Model;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace enterprise.Website.Core
{
    /// <summary>
    /// 获取网站基础信息类
    /// </summary>
    public class BaseWebElement
    {
        private readonly SqlContext _sqlContext;
        private readonly ICache _cache;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private LanguageType _currentlanguage;//当前语言版本
        public BaseWebElement(SqlContext sqlContext, ICache cache, IHttpContextAccessor httpContextAccessor)
        {
            _sqlContext = sqlContext;
            _cache = cache;
            _httpContextAccessor = httpContextAccessor;
            Init();
        }

        /// <summary>
        /// 当前语言信息
        /// </summary>
        public LanguageType Currentlanguage
        {
            get
            {
                return _currentlanguage;
            }
        }

        /// <summary>
        /// 需要语言分类的网站信息
        /// </summary>
        public static List<int> NeedLangguage = new List<int>
                {
                    (int)WebElementType.CompanyName,
                    (int)WebElementType.WebSeoKey,
                    (int)WebElementType.WebSeoDescription,
                    (int)WebElementType.Address,
                    (int)WebElementType.RecordInformation
                };

        /// <summary>
        /// 上传图片的网站信息
        /// </summary>
        public static List<int> NeedImg = new List<int>
                {
                    (int)WebElementType.Logo,
                    (int)WebElementType.Wechat
                };


        private void Init()
        {
            var languageType = GetLanguageType();
            if (languageType != null)
            {
                var CurrentLanguageClass = GetlanguageClass();
                if (!CurrentLanguageClass.IsNullOrWhiteSpace())
                {
                    _currentlanguage = languageType.Where(m => m.LanguageClass == CurrentLanguageClass).FirstOrDefault();
                    if (_currentlanguage == null)
                    {
                        languageType = _sqlContext.QueryList<LanguageType>();
                        _currentlanguage = languageType.Where(m => m.LanguageClass == CurrentLanguageClass).FirstOrDefault();
                    }
                }
                else
                {
                    _currentlanguage = languageType.OrderByDescending(m => m.IsDefault).FirstOrDefault();
                }
            }
        }

        /// <summary>
        /// 获取当前语言Href
        /// </summary>
        /// <returns></returns>
        public string GetCurrentlanguageclassHref()
        {
            return _currentlanguage.IsDefault == 1 ? "/" : "/" + _currentlanguage.LanguageClass + "/";
        }

        /// <summary>
        /// 获取去掉语言路径的当前路径
        /// </summary>
        /// <returns></returns>
        public string GetNotLanguageRoute()
        {
            var result = "/";
            var routeValues = _httpContextAccessor.HttpContext.Request.Path;
            if (routeValues.HasValue)
            {
                if (routeValues.Value.Contains(Currentlanguage.LanguageClass))
                {
                    result = routeValues.Value.Replace("/" + Currentlanguage.LanguageClass, "");
                }
                else
                {
                    result = routeValues.Value;
                }
            }
            return result;
        }

        /// <summary>
        /// 获取当前位置路径
        /// </summary>
        /// <param name="ClassId"></param>
        /// <returns></returns>
        public List<CurrentModel> GetCurrentRoute(int ClassId)
        {
            var result = new List<CurrentModel>();
            var contentClass = GetContentClass().Where(m => m.Id == ClassId).FirstOrDefault();
            if (contentClass!=null)
            {
                if (contentClass.ParentId != 0)
                {
                    result.AddRange(GetParentClass(contentClass.ParentId));
                }
                var href = string.Empty;
                if (contentClass.ClassType == (int)ClassType.News)
                {
                    if (contentClass.ParentId == 0)
                    {
                        href = "news";
                    }
                    else
                    {
                        href = "news/catelog/" + contentClass.Id + ".html";
                    }
                }
                else if (contentClass.ClassType == (int)ClassType.Products)
                {
                    if (contentClass.ParentId == 0)
                    {
                        href = "products";
                    }
                    else
                    {
                        href = "products/catelog/" + contentClass.Id + ".html";
                    }
                }
                else
                {
                    href = contentClass.Path;
                }
                result.Add(new CurrentModel
                {
                    ClassName = contentClass.ClassName,
                    ClassId = contentClass.Id,
                    ClassHref = GetCurrentlanguageclassHref() + href,
                });
            }
            return result;
        }

        /// <summary>
        /// 获取当前语言版本
        /// </summary>
        /// <returns></returns>
        public string GetlanguageClass()
        {
            if (_httpContextAccessor.HttpContext.Request.RouteValues.ContainsKey("languageClass"))
            {
                return _httpContextAccessor.HttpContext.Request.RouteValues["languageClass"].ToString().ToLower();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 是否在这个路径里(用于标红当前选项卡)
        /// </summary>
        /// <returns></returns>
        public bool IsOnPath(string Path)
        {
            var path = _httpContextAccessor.HttpContext.Request.Path.ToString();
            if (path.ToLower().Contains(Path.ToLower()))
            {
                return true;
            }
            if (_httpContextAccessor.HttpContext.Request.RouteValues.ContainsKey("path"))
            {
                var ContentClassList = GetContentClass();
                var onContentClass = ContentClassList.Where(m => m.Path == Path).OrderByDescending(m => m.Sort).FirstOrDefault();
                if (onContentClass != null)
                {
                    var contentClass = ContentClassList.Where(m => m.Path == _httpContextAccessor.HttpContext.Request.RouteValues["path"].ToString()).OrderByDescending(m => m.Sort).FirstOrDefault();
                    if (contentClass != null)
                    {
                        var route = GetCurrentRoute(contentClass.Id);
                        return route.Where(m => m.ClassId == onContentClass.Id).Count() > 0;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 获取所有的语言类型
        /// </summary>
        /// <returns></returns>
        public List<LanguageType> GetLanguageType()
        {
            var languageType = _cache.Get<List<LanguageType>>(SystemConstConfig.CacheLanguageType);
            if (languageType == null)//没有找到就读取数据库内数据,并缓存至内存
            {
                languageType = _sqlContext.QueryList<LanguageType>();
                if (languageType != null)
                {
                    _cache.Set(SystemConstConfig.CacheLanguageType, languageType, SystemConstConfig.ExpiressAbsoulte);
                }
            }
            return languageType;
        }

        /// <summary>
        /// 获取公司名称
        /// </summary>
        /// <returns></returns>
        public string GetCompanyName()
        {
            string CompanyName = string.Empty;
            //读取缓存中得网站信息和语言信息
            var webElement = GetWebElement();
            //找到默认得语言
            WebElement CompanyNameInfo = webElement.Where(m => m.Type == (int)WebElementType.CompanyName).OrderByDescending(m => m.Sort).FirstOrDefault();
            //如果没有名称则返回企业网站
            CompanyName = CompanyNameInfo != null ? CompanyNameInfo.Value : "企业网站";
            if (CompanyName.IsNullOrWhiteSpace())
            {
                CompanyName = "企业网站";
            }
            return CompanyName;
        }

        /// <summary>
        /// 获取网站元素信息
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public WebElement GetWebElement(WebElementType type)
        {
            var webElement = GetWebElement();
            WebElement webElementInfo = null;
            if (NeedLangguage.Contains((int)type))
            {
                webElementInfo = webElement.Where(m => m.Type == (int)type && m.LanguageId == _currentlanguage.Id).OrderByDescending(m => m.Sort).FirstOrDefault();
            }
            else
            {
                webElementInfo = webElement.Where(m => m.Type == (int)type).OrderByDescending(m => m.Sort).FirstOrDefault();
            }
            return webElementInfo;
        }

        /// <summary>
        /// 获取对应得中英文对照
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string QueryLanText(string key,int? languageId = null)
        {
            if (_currentlanguage == null)
            {
                return key;
            }
            var language = 0;
            if (languageId.HasValue)
            {
                language = languageId.Value;
            }
            else
            {
                language = _currentlanguage.Id;
            }
            var result = _cache.Get<string>($"{SystemConstConfig.LanguageText}_{language}_{key}");
            if (result.IsNullOrWhiteSpace())
            {
                var LanguageTextInfo = _sqlContext.QueryInfo<LanguageText>(m => m.Key == key && m.LanguageId == language);
                if (LanguageTextInfo != null)
                {
                    result = LanguageTextInfo.Value;
                    _cache.Set<string>($"{SystemConstConfig.LanguageText}_{language}_{key}", LanguageTextInfo.Value);
                }
                else
                {
                    return key;
                }
            }
            return result;
        }

        /// <summary>
        /// 获取首页配置
        /// </summary>
        /// <returns></returns>
        public WebHome GetWebHome()
        {
            var result = _cache.Get<WebHome>($"{SystemConstConfig.WebHomeKey}_{_currentlanguage.Id}");
            if (result == null)
            {
                result = _sqlContext.QueryInfo<WebHome>(m => m.LanguageId == _currentlanguage.Id);
                if (result != null)
                {
                    _cache.Set<WebHome>($"{SystemConstConfig.WebHomeKey}_{_currentlanguage.Id}", result);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取网站信息列表
        /// </summary>
        public List<WebElement> GetWebElement()
        {
            var result = _cache.Get<List<WebElement>>($"{SystemConstConfig.CacheWebElement}");
            if (result == null)
            {
                result = _sqlContext.QueryList<WebElement>(orderBy: "Sort desc");
                if (result != null)
                {
                    _cache.Set<List<WebElement>>($"{SystemConstConfig.CacheWebElement}", result, SystemConstConfig.ExpiressAbsoulte);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取网站栏目
        /// </summary>
        /// <returns></returns>
        public List<ContentClass> GetContentClass()
        {
            var result = _cache.Get<List<ContentClass>>($"{SystemConstConfig.ContentClassKey}_{_currentlanguage.Id}");
            if (result == null)
            {
                result = _sqlContext.QueryList<ContentClass>(m => m.LanguageId == _currentlanguage.Id, orderBy: "Sort desc");
                if (result != null)
                {
                    _cache.Set<List<ContentClass>>($"{SystemConstConfig.ContentClassKey}_{_currentlanguage.Id}", result, SystemConstConfig.ExpiressAbsoulte);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取首页Banner
        /// </summary>
        /// <returns></returns>
        public List<Banner> GetBanner()
        {
            var result = _cache.Get<List<Banner>>($"{SystemConstConfig.BannerKey}_{_currentlanguage.Id}");
            if (result == null)
            {
                result = _sqlContext.QueryList<Banner>(m => m.LanguageId == _currentlanguage.Id, orderBy: "Sort desc");
                if (result != null)
                {
                    _cache.Set<List<Banner>>($"{SystemConstConfig.BannerKey}_{_currentlanguage.Id}", result, SystemConstConfig.ExpiressAbsoulte);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取友情链接
        /// </summary>
        /// <returns></returns>
        public List<FriendLink> GetFriendLink()
        {
            var result = _cache.Get<List<FriendLink>>($"{SystemConstConfig.FriendLinkKey}_{_currentlanguage.Id}");
            if (result == null)
            {
                result = _sqlContext.QueryList<FriendLink>(m => m.LanguageId == _currentlanguage.Id, orderBy: "Sort desc");
                if (result != null)
                {
                    _cache.Set<List<FriendLink>>($"{SystemConstConfig.FriendLinkKey}_{_currentlanguage.Id}", result, SystemConstConfig.ExpiressAbsoulte);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取新闻(最新的10条)
        /// </summary>
        /// <returns></returns>
        public List<News_Info> GetNewsInfos()
        {
            var result = _cache.Get<List<News_Info>>($"{SystemConstConfig.News}_{_currentlanguage.Id}");
            if (result == null)
            {
                var datalist = _sqlContext.QueryPageList<News_Info>(m => m.LanguageId == _currentlanguage.Id && m.IsShow == 1, orderBy: "Id desc", 1, 15);
                if (datalist.count > 0 && datalist.data != null && datalist.data.Count() > 0)
                {
                    result = datalist.data.ToList();
                }
                if (result != null)
                {
                    _cache.Set<List<News_Info>>($"{SystemConstConfig.News}_{_currentlanguage.Id}", result, SystemConstConfig.ExpiressAbsoulte);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取产品(缓存)
        /// </summary>
        /// <returns></returns>
        public List<Product_Info> GetProducts()
        {
            var result = _cache.Get<List<Product_Info>>($"{SystemConstConfig.Products}_{_currentlanguage.Id}");
            if (result == null)
            {
                var datalist = _sqlContext.QueryPageList<Product_Info>(m => m.LanguageId == _currentlanguage.Id && m.IsShow == 1, orderBy: "Sort desc", 1, 10);
                if (datalist.count > 0 && datalist.data != null&& datalist.data.Count() > 0)
                {
                    result = datalist.data.ToList();
                }
                if (result != null)
                {
                    foreach (var pro in result)
                    {
                        var productImg = _sqlContext.QueryList<Product_Img>(m => m.ProId == pro.Id);
                        if (productImg != null && productImg.Count > 0)
                        {
                            pro.ProductImgs = productImg;
                            pro.TitleImg = productImg.OrderByDescending(m => m.IsTitle).FirstOrDefault().Img;
                        }
                    }
                    _cache.Set<List<Product_Info>>($"{SystemConstConfig.Products}_{_currentlanguage.Id}", result, SystemConstConfig.ExpiressAbsoulte);
                }
            }
            if (result == null)
            {
                return new List<Product_Info>();
            }
            return result;
        }


        private List<CurrentModel> GetParentClass(int ParentId)
        {
            var result = new List<CurrentModel>();
            var contentClass = GetContentClass().Where(m => m.Id == ParentId).FirstOrDefault();
            if (contentClass != null)
            {
                if (contentClass.ParentId != 0)
                {
                    result.AddRange(GetParentClass(contentClass.ParentId));
                }
                var href = string.Empty;
                if (contentClass.ClassType == (int)ClassType.News)
                {
                    if (contentClass.ParentId == 0)
                    {
                        href = "news";
                    }
                    else
                    {
                        href = "news/catelog/" + contentClass.Id + ".html";
                    }
                }
                else if (contentClass.ClassType == (int)ClassType.Products)
                {
                    if (contentClass.ParentId == 0)
                    {
                        href = "products";
                    }
                    else
                    {
                        href = "products/catelog/" + contentClass.Id + ".html";
                    }
                }
                else
                {
                    href = contentClass.Path;
                }
                result.Add(new CurrentModel
                {
                    ClassName = contentClass.ClassName,
                    ClassId = contentClass.Id,
                    ClassHref = GetCurrentlanguageclassHref() + href,
                });
            }
            return result;
        }
    }
}
